import java.io.*;
import java.net.*;
import java.util.*;

public class ConnectionProcessor2 implements Runnable
{
  private EM_Server2 server;

  private Socket socket;

  private DataInputStream din;

  private DataOutputStream dout;

  private static String BDuser = "expManager";
  private static String BDpassword = "pxCloud2011";

  public ConnectionProcessor2( EM_Server2 server, Socket socket ) {
    this.server = server;
    this.socket = socket;

    new Thread( this ).start();
  }
  
  public void run() {
    try {
      InputStream in = socket.getInputStream();
      OutputStream out = socket.getOutputStream();

      din = new DataInputStream( in );
      dout = new DataOutputStream( out );

   
      int id = din.readInt();
      int nFiles = din.readInt();
      File dir = new File(Integer.toString(id)+"Res");
      dir.mkdirs();
      System.out.println("Created directory "+dir);
      for (int i=0;i<nFiles;i++){
	FileWriter fstream = new FileWriter(id+"Res/"+din.readUTF());
	BufferedWriter bout = new BufferedWriter(fstream);
	String dades = din.readUTF();
	while (!dades.equals("Fin!")){
	  bout.write(dades);
	  bout.newLine();
	  dades = din.readUTF();
	}
	bout.close();
      
      }
    
    //Actualizamos el estado del experimento en la BBDD.  
    GestorBD gestorbd = new GestorBD();
        gestorbd.modificar("em", BDuser, BDpassword,
          "UPDATE em.EXPERIMENTS SET RESULTATS = '"+id+"Res', STATUS = 'Finalitzat' WHERE id = "+id+";");
    
    } catch( Exception ie ) {
      try {
        socket.close();
      } catch( IOException ie2 ) {
        System.out.println( "Error closing socket "+socket );
      }

      server.removeConnection( this );

      System.out.println( "Closed connection from socket "+socket );
    }
  }

}
